package cn.edu.cidp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/webgist2025_war_exploded/regservlet")
public class regservlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/personal_info_db?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        Map<String, Object> result = new HashMap<>();
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            // 1. 读取表单参数
            Map<String, String> formData = new HashMap<>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);
                formData.put(paramName, paramValue);
            }

            // 2. 验证必填字段
            if (formData.get("fullName") == null || formData.get("fullName").trim().isEmpty() ||
                    formData.get("gender") == null || formData.get("birthdate") == null ||
                    formData.get("idNumber") == null || formData.get("phone") == null) {
                result.put("success", false);
                result.put("message", "注册失败：请填写所有必填字段");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                try (PrintWriter out = response.getWriter()) {
                    out.print(toJsonString(result));
                }
                return;
            }

            // 3. 验证身份证号格式（示例：仅验证长度，实际项目需更严格）
            String idNumber = formData.get("idNumber");
            if (idNumber.length() != 18 && idNumber.length() != 15) {
                result.put("success", false);
                result.put("message", "注册失败：身份证号格式不正确");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                try (PrintWriter out = response.getWriter()) {
                    out.print(toJsonString(result));
                }
                return;
            }

            // 4. 验证手机号码格式
            String phone = formData.get("phone");
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                result.put("success", false);
                result.put("message", "注册失败：手机号码格式不正确");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                try (PrintWriter out = response.getWriter()) {
                    out.print(toJsonString(result));
                }
                return;
            }

            // 5. 连接数据库并插入数据
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            String sql = "INSERT INTO personal_information " +
                    "(full_name, gender, birthdate, id_number, phone, email, address) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 6. 设置参数（与前端字段名严格匹配）
            pstmt.setString(1, formData.get("fullName"));
            pstmt.setString(2, formData.get("gender").equals("male") ? "男" : "女"); // 存储中文性别
            pstmt.setString(3, formData.get("birthdate"));
            pstmt.setString(4, formData.get("idNumber"));
            pstmt.setString(5, formData.get("phone"));
            pstmt.setString(6, formData.get("email"));
            pstmt.setString(7, formData.get("address"));

            // 7. 执行插入
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                result.put("success", true);
                result.put("message", "注册成功");
                result.put("userId", getLastInsertId(conn));
                response.setStatus(HttpServletResponse.SC_CREATED);
            } else {
                result.put("success", false);
                result.put("message", "注册失败：数据未插入");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

        } catch (SQLException e) {
            // 处理数据库异常（如唯一约束冲突）
            result.put("success", false);
            if (e.getMessage().contains("Duplicate entry")) {
                result.put("message", "注册失败：该身份证号或手机号已被注册");
            } else {
                result.put("message", "注册失败：数据库错误 - " + e.getMessage());
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他异常
            result.put("success", false);
            result.put("message", "注册失败：系统错误 - " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 返回JSON响应
        try (PrintWriter out = response.getWriter()) {
            out.print(toJsonString(result));
        }
    }

    /**
     * 获取最后插入的记录ID
     */
    private long getLastInsertId(Connection conn) throws SQLException {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()")) {
            if (rs.next()) {
                return rs.getLong(1);
            }
            return -1;
        }
    }

    /**
     * 将Map转换为JSON字符串（简化实现，实际项目建议使用JSON库）
     */
    private String toJsonString(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean firstEntry = true;

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!firstEntry) {
                json.append(",");
            }
            json.append("\"").append(entry.getKey()).append("\":");

            Object value = entry.getValue();
            if (value instanceof String) {
                // 转义字符串中的特殊字符
                String escapedValue = ((String) value)
                        .replace("\\", "\\\\")
                        .replace("\"", "\\\"")
                        .replace("\n", "\\n")
                        .replace("\r", "\\r")
                        .replace("\t", "\\t");
                json.append("\"").append(escapedValue).append("\"");
            } else if (value instanceof Number || value instanceof Boolean) {
                json.append(value.toString());
            } else if (value == null) {
                json.append("null");
            } else {
                json.append("\"").append(value.toString()).append("\"");
            }

            firstEntry = false;
        }

        json.append("}");
        return json.toString();
    }
}